package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"law_case_api/services"
	"law_case_api/utils"
	"net/http"
	"strconv"
	"time"
)

// CreateCustomerEvent
// @Summary 创建客户事项信息
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param CreateCustomerEvent body dto.ContractEventReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/event/create [post]
func CreateCustomerEvent(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	customerEventReq := dto.CustomerEventReq{}
	if err := c.Bind(&customerEventReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	wzjCustomerEvent := models.WzjCustomerEvent{}
	utils.MapTo(customerEventReq, &wzjCustomerEvent)
	wzjCustomerEvent.CreateUserId = int64(userid)
	wzjCustomerEvent.CreateDate = time.Now().Unix()

	customer := services.CustomerService{}
	boolRes, err := customer.CreateCustomerEvent(wzjCustomerEvent)
	if err == nil && boolRes {
		resp.Message = "创建客户事项记录成功"
		return c.JSON(http.StatusOK, resp)
	}
	log.Error("创建客户事项记录失败：", err) //增加日志信息
	resp.Code = 400
	resp.Message = "创建客户事项记录失败"
	return c.JSON(http.StatusOK, resp)
}

// GetCustomerEventList
// @Summary 获取客户事项信息列表
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param customerId query string true "客户id"
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/event/list [get]
func GetCustomerEventList(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	customerId, _ := strconv.Atoi(c.QueryParam("customerId"))
	if customerId == 0 {
		resp.Code = 400
		resp.Message = "客户编号不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	customer := services.CustomerService{}

	customerEventList, _, err := customer.GetCustomerEventListByCustomerId(customerId)
	if err != nil {
		resp.Code = 400
		resp.Message = "根据客户编号获取客户事项记录列表失败"
		return c.JSON(http.StatusOK, resp)
	}
	//格式化
	customerEventResp := []dto.CustomerEventResp{}
	_ = utils.MapTo(customerEventList, &customerEventResp)
	resp.Data = customerEventResp
	return c.JSON(http.StatusOK, resp)
}
